package com.linzhiot;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.*;
import org.flowable.engine.runtime.Execution;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.image.ProcessDiagramGenerator;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class FlowableService {
    @Autowired
    RuntimeService runtimeService;
    @Autowired
    TaskService taskService;
    @Autowired
    RepositoryService repositoryService;
    @Autowired
    ProcessEngine processEngine;

    public Map<String, String> start(FlowableStartProcessInfo info) {
        ProcessInstance processInstance;
        List<ProcessInstance> instances = runtimeService.createProcessInstanceQuery()
                .processDefinitionKey(info.processDefinitionKey).variableValueEquals("name", info.name).list();
        if (instances.size() > 0) {
            processInstance = instances.get(0);
        } else {
            Map<String, Object> params = new HashMap<>(0);
            params.put("name", info.name);
            if (info.serviceTaskUrl != null) {
                params.put("serviceTaskUrl", info.serviceTaskUrl);
            }
            if (info.params != null) {
                params.putAll(info.params);
            }
            processInstance =
                    runtimeService.startProcessInstanceByKey(info.processDefinitionKey, params);
        }
        Map<String, String> ret = new HashMap<>();
        ret.put("processName",info.name);
        ret.put("processId",processInstance.getId());
        return ret;
    }

    public List<FlowableProcessInfo> listProcesses(String processDefinitionKey) {
        List<Execution> executions = runtimeService.createExecutionQuery().onlyChildExecutions().processDefinitionKey(processDefinitionKey).list();
        Map<String, List<FlowableProcessInfo.TaskInfo>> mapProcessTasks = new HashMap<>(0);
        executions.forEach(e -> {
            if (!mapProcessTasks.containsKey(e.getProcessInstanceId())) {
                mapProcessTasks.put(e.getProcessInstanceId(), new ArrayList<>(0));
            }
            List<FlowableProcessInfo.TaskInfo> tasks = taskService.createTaskQuery().executionId(e.getId()).list().stream().map(t -> {
                FlowableProcessInfo.TaskInfo task = new FlowableProcessInfo.TaskInfo();
                task.id = t.getId();
                task.definitionKey = t.getTaskDefinitionKey();
                task.name = t.getName();
                return task;
            }).collect(Collectors.toList());
            mapProcessTasks.get(e.getProcessInstanceId()).addAll(tasks);
        });
        List<ProcessInstance> processInstances = runtimeService.createProcessInstanceQuery().processDefinitionKey(processDefinitionKey).list();
        return processInstances.stream().map(p -> {
            FlowableProcessInfo info = new FlowableProcessInfo();
            info.processInstanceId = p.getId();
            info.processName = (String)runtimeService.getVariables(p.getId()).get("name");
            if (mapProcessTasks.containsKey(p.getProcessInstanceId())) {
                info.tasks = mapProcessTasks.get(p.getProcessInstanceId());
            }
            return info;
        }).collect(Collectors.toList());
    }

    public List<FlowableProcessInfo> taskList(String userId) {
        List<Task> tasks = taskService.createTaskQuery().taskAssignee(userId).orderByTaskCreateTime().desc().list();
        return tasks.stream().map(task -> {
            FlowableProcessInfo flowableProcessInfo = new FlowableProcessInfo();
            flowableProcessInfo.processInstanceId = task.getProcessInstanceId();
            flowableProcessInfo.processName = task.getName();
            flowableProcessInfo.tasks = new ArrayList<>();
            FlowableProcessInfo.TaskInfo taskInfo = new FlowableProcessInfo.TaskInfo();
            taskInfo.name = task.getName();
            taskInfo.id = task.getId();
            taskInfo.definitionKey = task.getTaskDefinitionKey();
            flowableProcessInfo.tasks.add(taskInfo);
            return flowableProcessInfo;
        }).collect(Collectors.toList());
    }

    public Task getTaskByTaskId(String taskId){
        return taskService.createTaskQuery().taskId(taskId).singleResult();
    }
    public void genProcessDiagram( String processId) throws Exception {
        ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();

        //流程走完的不显示图
        if (pi == null) {
            return;
        }
        Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
        //使用流程实例ID，查询正在执行的执行对象表，返回流程实例对象
        String InstanceId = task.getProcessInstanceId();
        List<Execution> executions = runtimeService
                .createExecutionQuery()
                .processInstanceId(InstanceId)
                .list();

        //得到正在执行的Activity的Id
        List<String> activityIds = new ArrayList<>();
        List<String> flows = new ArrayList<>();
        for (Execution exe : executions) {
            List<String> ids = runtimeService.getActiveActivityIds(exe.getId());
            activityIds.addAll(ids);
        }

        //获取流程图
        BpmnModel bpmnModel = repositoryService.getBpmnModel(pi.getProcessDefinitionId());
        ProcessEngineConfiguration engconf = processEngine.getProcessEngineConfiguration();
        ProcessDiagramGenerator diagramGenerator = engconf.getProcessDiagramGenerator();
        InputStream in = diagramGenerator.generateDiagram(bpmnModel, "png", activityIds, flows, engconf.getActivityFontName(), engconf.getLabelFontName(), engconf.getAnnotationFontName(), engconf.getClassLoader(), 1.0, true);
        OutputStream out = null;
        byte[] buf = new byte[1024];
        int legth;
//        try {
//            out = httpServletResponse.getOutputStream();
//            while ((legth = in.read(buf)) != -1) {
//                out.write(buf, 0, legth);
//            }
//        } finally {
//            if (in != null) {
//                in.close();
//            }
//            if (out != null) {
//                out.close();
//            }
//        }
    }

    public void completeTask(String taskId) {
        taskService.complete(taskId);
    }

    public void completeTask(String taskId, Map<String, Object> var) {
        taskService.complete(taskId, var);
    }
}
